package com.ruoyi.mp.service;

import com.ruoyi.ai.factory.ModelChatService;
import com.ruoyi.ai.factory.ModelChatStrategyFactory;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.mp.domain.bo.MpArticleBo;
import com.ruoyi.mp.domain.vo.MpArticleVo;
import com.ruoyi.mp.enums.MpAricleStatusEnum;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.draft.WxMpAddDraft;
import me.chanjar.weixin.mp.bean.draft.WxMpDraftArticles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class AIMpArticleService {
    @Autowired
    private IMpArticleService mpArticleService;
    @Autowired
    private IMpMaterialService mpMaterialService;
    @Autowired
    private WxMpService wxMpService;

    private static final String ARTICLE_PROMPT_TEMPLATE = "你是一位拥有10年Java开发经验的技术专家，同时也是科技类公众号的资深撰稿人。请根据主题【%s】撰写一篇适合程序员阅读的技术解析文章，要求如下：\n" +
        "\n" +
        "# 格式规范\n" +
        "【标题】独占第一行（使用吸引人的疑问句/热点结合句式）\n" +
        "【摘要】第二段落用50字左右阐明文章价值\n" +
        "---\n" +
        "# 内容框架\n" +
        "## 一、核心原理剖析\n" +
        "• 结合源码片段讲解实现机制（附关键代码示例）\n" +
        "• 用生活化比喻解释技术概念\n" +
        "\n" +
        "## 二、典型应用场景\n" +
        "\n" +
        "## 三、高频问题精解\n" +
        "列出开发者最常遇到的几个问题，每个问题包含：\n" +
        "✓ 问题现象（错误日志示例）\n" +
        "✓ 排查流程图\n" +
        "✓ 解决方案代码片段\n" +
        "\n" +
        "# 风格要求\n" +
        "• 采用技术博主口语化风格（适当使用emoji符号\uD83C\uDF1F\uD83D\uDCA1⚠\uFE0F）\n" +
        "• 专业性与可读性平衡（复杂概念用表格对比说明）\n" +
        "• 避免AI生成痕迹（禁用\"首先/其次/最后\"等刻板结构）\n" +
        "• 每段落不超过200字，代码块用```java标记";

    /**
     * 自动发布公众号文章
     *
     * @param id       文章id，为空则取最新的
     * @param reCreate 是否重新创建，如果为true，则重新走遍流程，否则已存在内容则不执行
     */
    public void autoPubMpArticle(Long id, Boolean reCreate) {
        MpArticleVo articleVo = getOneArticle(id);
        if (articleVo == null) {
            throw new ServiceException("目前没有可创建内容的文章");
        }
        Boolean checkCoverMediaId = checkCoverMediaId(articleVo);
        if (checkCoverMediaId) {
            throw new ServiceException("请先设置封面图");
        }
        String prompt = generatePrompt(articleVo);
        generateArticle(articleVo, prompt);
        beautifyArticle(articleVo);
        uploadArticle(articleVo);
    }
    //TODO
    //1.获取一个待创建的文章
    //2.检测是否有封面图id
    //3.生成prompt提示词
    //4.调用AI生成文章，md格式
    //5.保存文章到数据库
    //6.美化文章,并保存到数据库
    //7.上传文章到公众号，保存为草稿，人工核验后发布

    public MpArticleVo getOneArticle(Long id) {
        if (id != null) {
            return mpArticleService.queryById(id);
        }
        return mpArticleService.queryFarthestUncreatedArticle();
    }

    public Boolean checkCoverMediaId(MpArticleVo mpArticleVo) {
        String coverMediaId = mpArticleVo.getCoverMediaId();
        if (StringUtils.isBlank(coverMediaId)) {
            return false;
        }
        return true;
    }

    public String generatePrompt(MpArticleVo mpArticleVo) {
        String theme = mpArticleVo.getTheme();
        return String.format(ARTICLE_PROMPT_TEMPLATE, theme);
    }

    public void generateArticle(MpArticleVo mpArticleVo, String prompt) {
        ModelChatService modelChatService = ModelChatStrategyFactory.getEnableMfg();
        String s = modelChatService.chatStreamOnce(prompt);
        updateArticle(mpArticleVo.getId(), s, null, MpAricleStatusEnum.UN_BEAUTY.getType(), null);
    }

    public void beautifyArticle(MpArticleVo mpArticleVo) {
        String beautifyContent = mpArticleVo.getContentHtml();
        updateArticle(mpArticleVo.getId(), null, beautifyContent, MpAricleStatusEnum.UN_UP.getType(), null);
    }

    private void uploadArticle(MpArticleVo mpArticleVo) {
        WxMpAddDraft draft = new WxMpAddDraft();
        List<WxMpDraftArticles> articles = new ArrayList<>();
        WxMpDraftArticles wxMpDraftArticles = new WxMpDraftArticles();
        wxMpDraftArticles.setContent(mpArticleVo.getContent());
        wxMpDraftArticles.setTitle(mpArticleVo.getTitle());
        wxMpDraftArticles.setAuthor("不知不觉YH");
        wxMpDraftArticles.setThumbMediaId(mpArticleVo.getCoverMediaId());
        articles.add(wxMpDraftArticles);
        draft.setArticles(articles);
        try {
            String mediaId = wxMpService.getDraftService().addDraft(draft);
            updateArticle(mpArticleVo.getId(), null, null, MpAricleStatusEnum.UN_PUBLISH.getType(), mediaId);
        } catch (WxErrorException e) {
            log.error("上传草稿失败==>" + e.getMessage());
            throw new ServiceException("上传草稿失败==>" + e.getMessage());
        }
    }

    private Boolean updateArticle(Long id, String content, String contentHtml, Integer status, String draftMediaId) {
        MpArticleBo bo = new MpArticleBo();
        bo.setId(id);
        bo.setContent(content);
        bo.setContentHtml(contentHtml);
        bo.setStatus(status);
        bo.setDraftMediaId(draftMediaId);
        return mpArticleService.updateByBo(bo);
    }
}
